﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;

using System.Data.Linq;
using MvcEngine.Core.Common;
using MvcEngine.Core.Pagination;
using MvcEngine.Core.Base;

namespace MvcEngine.LinqToSqlProvider
{
    public class LogRepository : Repository, ILogRepository
    {
        public void Add(Log entity)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Logs().InsertOnSubmit(entity);
                contextManager.Commit();
            }
        }

        public IList<Log> GetAll(Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Logs().Where(l => l.SiteId == siteId).OrderByDescending(l => l.CreatedDate).ToList();
            }
        }

        public IPagination<Log> GetAll(Guid siteId, LoadOptions options)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Logs().Where(l => l.SiteId == siteId).OrderByDescending(l => l.CreatedDate).AsPagination(options.PageNumber, options.PageSize);
            }
        }

        public void DeleteAll(Guid siteId)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Logs().DeleteAllOnSubmit(contextManager.Context.Logs().Where(s => s.SiteId == siteId));
                contextManager.Commit();
            }
        }

        public Log Get(Guid id)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Logs().SingleOrDefault(l => l.Id == id);
            }
        }

        public void Delete(Guid id)
        {
            using (var contextManager = CreateContextManager(false))
            {
                var log = contextManager.Context.Logs().SingleOrDefault(l => l.Id == id);

                if (log != null)
                {
                    contextManager.Context.Logs().DeleteOnSubmit(log);
                    contextManager.Commit();
                }
            }
        }
    }
}
